package com.atguigu.juc.lockSupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yfstart
 * @create 2022-07-05 18:02
 */
public class LockSupportDemo {
  public static void main(String[] args) {
      // syncWaitNotify();
      // syncAwaitSignal();
      Thread t1 = new Thread(() -> {
          try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace();}
          System.out.println(Thread.currentThread().getName() + "\t ---come in\t" + System.currentTimeMillis());
          LockSupport.park();
          System.out.println(Thread.currentThread().getName() + "\t ---被唤醒\t" + System.currentTimeMillis());
      }, "t1");
      t1.start();

      // try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace();}

      new Thread(()->{
          LockSupport.unpark(t1);
          System.out.println(Thread.currentThread().getName() + "\t ---发通知\t" + System.currentTimeMillis());
      },"t2").start();
  }

    private static void syncAwaitSignal() {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(()->{
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t ---come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "\t ---被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t1").start();

        try { TimeUnit.MILLISECONDS.sleep(2000); } catch (InterruptedException e) { e.printStackTrace();}

        new Thread(()->{
            lock.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + "\t ---发通知");
            } finally {
              lock.unlock();
            }
        },"t2").start();
    }

    private static void syncWaitNotify() {
    Object objectLock = new Object();
    new Thread(()->{
        synchronized (objectLock){
            System.out.println(Thread.currentThread().getName() + "\t ---come in");
            try {
                objectLock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t ---被唤醒");
        }
    },"t1").start();

    try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { e.printStackTrace();}

    new Thread(()->{
        synchronized (objectLock){
            objectLock.notify();
            System.out.println(Thread.currentThread().getName() + "\t ---发通知");
        }
    },"t2").start();
  }
}